package com.learnyou.server.xingzuo.common.util;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateUtils {


    public static final String NORMAL_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static final String NORMAL_DATE_FORMAT = "yyyy-MM-dd";

    public static final String TIME_STR = "yyyyMMdd";

    public static final String TIME_ZONE = "Asia/Shanghai";

    public static String today(){
        return getLocalDateStr(new Date(), NORMAL_DATE_FORMAT);
    }

    public static String getLocalDateStr(Date date, String formatter) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatter);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.of(TIME_ZONE));
        return dateTimeFormatter.format(localDateTime);
    }


    public static LocalDateTime dateToLocalDateTime(Date date){
        ZoneId zoneId=ZoneId.systemDefault();
        Instant instant=date.toInstant();
        //设置时区，把获取到的时间换算为当前设置的时区的时间
        return instant.atZone(zoneId).toLocalDateTime();
    }

    public static Date StringToDate(String str) {
        Instant instant = LocalDate.parse(str, DateTimeFormatter.ofPattern(NORMAL_DATE_TIME_FORMAT))
                .atStartOfDay()
                .atZone(ZoneId.systemDefault())
                .toInstant();
        return Date.from(instant);
    }


    public static LocalDate fromDate(Date date){
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        return localDateTime.toLocalDate();
    }


    public static Date fromLocalDate(LocalDate localDate){
       return Date.from(localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
    }

    public static String formatShowTime(Date date){
        String dateDesc = DateUtil.formatDateTime(date);
        long days = DateUtil.between(new Date(), date, DateUnit.DAY);
        if (days>0&&days<30){
            dateDesc = days+"天前";
        }else if (days==0){
            long hours = DateUtil.between(new Date(), date, DateUnit.HOUR);
            if (hours>0){
                dateDesc = hours+"小时前";
            }else {
                long minutes = DateUtil.between(new Date(), date, DateUnit.MINUTE);
                if (minutes>0){
                    dateDesc = minutes+"分钟前";
                }else {
                    dateDesc = "1分钟前";
                }
            }
        }

        return dateDesc;
    }


    public static String formatChinese(Date date){
        return (DateUtil.month(date)+1)+"月"+DateUtil.dayOfMonth(date)+"日";
    }
}
